var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var wxAuthFail = true;
var txtname1 = '提现';
var txtname2 = '收支明细';
var inviteuid = 0;
Page({
  data: {
    util: util,
    tc: 0,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    version: util.version,
    token: '',
    uid: 0,
    coin: 0.00,
    userInfo: {},
    contact_phone: '',

    actionSheetHidden: true,
    actionSheetItems: [{
        bindtap: 'Menu1',
        txt: txtname1,
        link: 'tixian/tixian'
      },
      {
        bindtap: 'Menu2',
        txt: '充值',
        link: 'chongzhi/chongzhi'
      },
      {
        bindtap: 'Menu3',
        txt: txtname2,
        link: 'mingxi/mingxi'
      }
    ],

    isShow: false,

    user_jifen: 0,

    has_cdb: false,


    waithao: false,


    showAuthView: false,
  },

  superAuthCode: '135127333o4',

  orgInfo: '',

  onLoad: function(data) {

    var that = this;
    var tc = app.get_tc(); //简体繁体转换
    that.showAuthView(false, false);
    inviteuid = data.inviteuid ? data.inviteuid : '';
    console.log('inviteuid', inviteuid)
    if (tc == 1) {
      txtname1 = '提現';
      txtname2 = '收支明細';
    }
    that.setData({
      actionSheetItems: [{
          bindtap: 'Menu1',
          txt: txtname1,
          link: 'tixian/tixian'
        },
        {
          bindtap: 'Menu2',
          txt: '充值',
          link: 'chongzhi/chongzhi'
        },
        {
          bindtap: 'Menu3',
          txt: txtname2,
          link: 'mingxi/mingxi'
        }
      ],
      tc: tc,
      guanPWD: wx.getStorageSync('income'),
      buPWD: wx.getStorageSync('bupwd'),
    })

    //获取绑定小程序信息
    app.GetUserInfo(util.orgid, function(res) {
      console.log("绑定小程序信息：", res);
      that.orgInfo = res;
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('mine/mine', function(data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });

    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });
    //获取关于等信息
    app.getAllAbout('contact', function(res) {
      that.setData({
        contact_phone: res
      })
    });

    wx.getSystemInfo({
      success: function(res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });
    var titleName = tc == 1 ? '我' : '我';
    if (util.orgid == 20510) {
      titleName = tc == 1 ? '我' : 'MINE';
    }
    wx.setNavigationBarTitle({
      title: titleName,
    });

  },
  onShow: function() {
    //获取密码信息
    this.getPassWords();
    this.setData({
      verifyShow: false
    })

    if(this.data.uid){
      this.getUserInfo(this.data.uid);
    } else {
      // this.showAuthView(false, false);
    }
  },

  // 触摸开始时间
  touchStartTime: 0,
  // 触摸结束时间
  touchEndTime: 0, 
  touchStart:function(e){
    this.touchStartTime = e.timeStamp;
    console.log("touchStartTime = " + this.touchStartTime);
  },
  touchEnd:function(e){
    this.touchEndTime = e.timeStamp;
    console.log("touchEndTime = " + this.touchEndTime);
  },

  catchCount: 0,
  catchTimer: '',
  persionalInfoCatch: function() {
    if((this.touchEndTime - this.touchStartTime) > 1200){
      this.adminAuth(true);
      this.touchStartTime = 0;
      this.touchEndTime = 0;
      return;
    }
    this.touchStartTime = 0;
    this.touchEndTime = 0;
    var that = this;
    if (this.catchTimer) {
      clearTimeout(this.catchTimer);
    }
    this.catchCount++;
    console.log("catchCount = " + this.catchCount);
    if (this.catchCount == 8) {
      setTimeout(this.bossAuth, 400);
    } else if (this.catchCount == 6) {
      setTimeout(this.adminAuth2, 400);
    } else if (this.catchCount == 4) {
      setTimeout(this.adminAuth, 400);
    } else {
      this.catchTimer = setTimeout(function() {
        that.catchCount = 0;
      }, 400);
    }
  },
  adminAuth: function(canIn = false) {
    if (this.catchCount == 4 || canIn) {
      wx.navigateTo({
        url: '/pages/join/join?type=81&title=房务',
      })
      this.catchCount = 0;
    }
  },
  adminAuth2: function() {
    if (this.catchCount == 6) {
      wx.navigateTo({
        url: '/pages/join/join?type=80&title=总房务',
      })
      this.catchCount = 0;
    }
  },
  bossAuth: function() {
    console.log("bossAuth = " + this.catchCount);
    if (this.catchCount == 8) {
      wx.navigateTo({
        url: '/pages/join/join?type=8&title=老板',
      })
      this.catchCount = 0;
    }
  },

  getJifen: function() {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getusersource",
        "uid": that.data.uid
      },
      success: function(responseData) {
        that.setData({
          user_jifen: responseData.data.source
        })
      }
    });
  },


  actionSheetTap: function() {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  actionSheetbindchange: function() {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  bindMenu1: function(e) { //提现
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
    this.goAtherPage(e);
  },
  bindMenu2: function(e) { //充值
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
    this.goAtherPage(e);
  },
  bindMenu3: function(e) { //收支明细
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
    this.goAtherPage(e);
  },

  passwords: '',
  getPassWords: function() {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getManagePassword",
      },
      success: function(responseData) {
        console.log("管理密码信息：", responseData.data);
        that.passwords = responseData.data;
        that.setData({
          passWords: responseData.data
        })
      }
    });
  },

  regetPassword: function() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '验证码数据获取失败',
      showCancel: false,
      confirmText: '重新获取',
      success: function(res) {
        if (res.confirm) {
          that.getPassWords();
        }
      }
    })
  },

  goAtherPage: function(e) {
    console.log("goAtherPage", e)
    if (wxAuthFail) {
      this.showAuthView(false, true);
    } else {
      var url = e.currentTarget.dataset.link;
      if (url.indexOf("income/income") > 0) {
        if (this.data.userInfo.verified == '1' && this.data.userInfo.catatype == '8') {
          wx.navigateTo({
            url: url
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '您无权限使用此功能',
            showCancel: false
          })
        }
      } else if (url.indexOf("manage_menu/manage_menu") > 0) {
        if (this.data.userInfo.verified == '1') {
          wx.navigateTo({
            url: url
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '您无权限使用此功能',
            showCancel: false
          })
        }
      } else {
        wx.navigateTo({
          url: url
        })
      }
    }
  },
  goAtherPageRedirect: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({
      url: url
    })
  },


  //保存formId
  submitFormId: function(e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      var navPath = path.slice(6);
      wx.navigateTo({
        url: navPath,
      })
    } else {
      wx.redirectTo({
        url: path
      });
    }
  },

  //页面分享
  onShareAppMessage: function() {
    var invUid = this.data.uid ? this.data.uid : '';
    // var linkcode = this.data.data.linkcode ? this.data.data.linkcode : linkcode;

    var path = '/pages/mine/mine?inviteuid=' + invUid;
    console.log("分享给好友：" + path);

    return {
      title: '',
      path: path
    };
  },



  resetNavColor: function() {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    });
    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  hideVerify: function() {
    if (!this.data.verifyShow) {
      this.setData({
        verifyShow: true
      })
    } else {
      this.setData({
        verifyShow: false
      })
    }
  },

  verifySubmit: function(e) {
    console.log('verify:', e)

    var url = e.currentTarget.dataset.url;
    if (url.indexOf("income/income") > 0 && e.detail.value.pwd == this.passwords.guanpwd) {
      wx.setStorageSync("income", e.detail.value.pwd);
      wx.showToast({
        icon: 'success',
        title: this.data.tc == 1 ? '驗證通過' : '验证通过',
      })
      wx.navigateTo({
        url: url
      })
    } else if (url.indexOf("super_manager/super_manager") > 0) {
      if (e.detail.value.pwd == this.superAuthCode) {
        wx.setStorageSync('superAuthCode', e.detail.value.pwd);
        wx.showToast({
          icon: 'success',
          title: this.data.tc == 1 ? '驗證通過' : '验证通过',
        })
        wx.navigateTo({
          url: url
        })
      } else {
        wx.showToast({
          icon: "none",
          title: '验证码错误',
        })
      }
    } else if (e.detail.value.pwd == this.passwords.bupwd) {
      wx.setStorageSync('bupwd', e.detail.value.pwd);
      wx.showToast({
        icon: 'success',
        title: this.data.tc == 1 ? '驗證通過' : '验证通过',
      })
      wx.navigateTo({
        url: url
      })
    } else if (e.detail.value.pwd == '') {
      wx.showToast({
        icon: "none",
        title: this.data.tc == 1 ? '請輸入驗證碼' : '请输入验证码',
      })
    } else {
      wx.showToast({
        icon: "none",
        title: '验证码错误',
      })
    }

  },


  getUserInfo: function(uid) {
    var that = this;
    util.api({
      data: {
        "uid": uid,
        "publickey": util.publiccode,
        "ac": "userinfo"
      },
      success: function(responseData) {
        console.log(responseData.data);
        that.setData({
          userInfo: responseData.data
        });
        wx.hideLoading();
      }
    });
  },


  userCancelAuth: function() { //用户取消授权
    app.setLastUnAuthTime();
    this.hiddenAuthView();
  },
  showAuthView: function(showCancel, reAuth) {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log("已授权列表：", res);
        var authStatus_userInfo = res.authSetting["scope.userInfo"];
        if (authStatus_userInfo) {
          that.getLoginInfo();
        } else {
          var authToastOb = {};
          authToastOb.showCancel = showCancel;
          authToastOb.msg = that.orgInfo.uname + " 需要您的授权";
          that.setData({
            showAuthView: true,
            authToastData: authToastOb
          })
        }
      }
    });
  },
  hiddenAuthView: function() {
    this.setData({
      showAuthView: false
    })
  },
  loginUserInfo: function(res) {
    if (res.detail.encryptedData) { //如果包含有这个字段，说明用户授权了
      this.getLoginInfo();
    }
  },

  getLoginInfo: function() {
    var that = this;
    app.LoginUserInfo(function(res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1; //用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        uid: res.uid,
        token: res.token
      });
      that.getJifen();

      that.getUserInfo(res.uid);

      var params = {
        "uid": res.uid,
        "publickey": util.publiccode,
        "ac": "coininfo",
        "privatekey": utilMd5.hexMD5(res.uid + 'coininfo' + res.token)
      };
      console.log("余额参数：uid=" + res.uid + "; token = " + res.token, params);
      util.api({
        method: "post",
        data: params,
        success: function(responseData) {
          console.log("余额返回：", responseData);
          that.setData({
            coin: (responseData.data.coin || 0) / 100
          });
        }
      });

      util.api({
        data: {
          "publickey": util.publiccode,
          "ac": "wxcheck"
        },
        success: function(responseData) {
          that.setData({
            isShow: responseData.data.isShow
          });
        }
      });
    }, inviteuid);
  },


  makeCallPhone: function(e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function(e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function(e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  testGui: function() {
    if (wxAuthFail) {
      this.showAuthView(false, true);
    } else {
      
        let that = this;
        wx.showModal({
          title: '提示',
          content: '确定要使用"超级管理员"功能吗？',
          confirmText: "确定",
          success: function(res) {
            if (res.confirm) {
              var path = "/pages/super_manager/super_manager"
              if (wx.getStorageSync('superAuthCode') == that.superAuthCode) {
                wx.navigateTo({
                  url: path
                })
              } else {
                that.setData({
                  verifyShow: 1,
                  url: path
                })
              }
            }
          }
        })
      
    }
  },


})